#!/bin/bash
#
# temporary sharing
#
# Data: 	15/05/2015 14:15:46
# Autore: 	Lorenzo Saibal Forti <saibal@lorenzone.it>
#
# Copyleft:	2010 - Tutti i diritti riservati
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#=====================================================================

# porta della condivisione
SHARING_PORT=8080

# tempo della condivisione (in secondi)
SHARING_TIME=60

# il tuo nome utente (serve per abilitare le notifiche se usate da cron. lascia vuoto se non vuoi usarle)
USERNAME_XAUTHORITY='saibal'

# ip lan via eth0. se non lo trovo provo su wlan0
LAN_IP=''

for INTERFACE in eth0 wlan0
do

	if [ -z "$LAN_IP" ]
	then
		LAN_IP=$(ifconfig $INTERFACE | grep inet | awk '{print $2}' | cut -d':' -f2)
	fi
done

# controllo l'esistenza di connessioni già attive
CHECK_SERVICE=$(ps ax | grep -v grep | grep "python -m SimpleHTTPServer $SHARING_PORT" | awk '{print $1}')

if [ -z "$CHECK_SERVICE" ]
then

	if [ "$USERNAME_XAUTHORITY" != "" ]
	then
		export XAUTHORITY="/home/$USERNAME_XAUTHORITY/.Xauthority"
		export DISPLAY=:0
	fi

	CWD=$(pwd)

	python -m SimpleHTTPServer $SHARING_PORT &

	S_PID=$!

	zenity --notification --title="Python Share" --timeout=15 --width=450 \
	--text "Condivisione attiva per $SHARING_TIME secondi :

$CWD
	
http://$LAN_IP:$SHARING_PORT"

	sleep $SHARING_TIME

	kill -s 15 $S_PID

	zenity --notification --title="Python Share" --timeout=5 \
	--text "Condivisione disattivata:

$CWD
	"
else

	zenity --question --title="Python Share" --text="Condivisione Python già esistente. Chiudere condivisione?"

	if [ $? -eq 0 ]
	then

		kill -s 15 $CHECK_SERVICE

		if [ $? -eq 0 ]
		then

			zenity --notification --title="Python Share" --width=300 --timeout=5 --text "Condivisioni chiuse"
		fi
	fi
fi

exit 0
